package com.example.educationplatformbackend.controller;


import com.example.educationplatformbackend.config.upload.UploadImageDIR;
import com.example.educationplatformbackend.config.upload.UploadProperties;
import com.example.educationplatformbackend.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@CrossOrigin
@RestController
@RequestMapping("/api")
public class UploadController {

    private final String requestPath;
    private final String UPLOAD_PATH;

    @Autowired
    public UploadController(UploadProperties uploadProperties) {
        this.requestPath = uploadProperties.getRequestPath();
        this.UPLOAD_PATH = uploadProperties.getUploadDir();
        // 确保这里的逻辑不会抛出异常
    }
    @CrossOrigin(origins = "*")
    @PostMapping("/upload/image")
    public ResponseResult<UploadImageDIR> handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {

            return ResponseResult.failure(HttpStatus.BAD_REQUEST, "文件为空");
        }

        try {

            // 确保目录存在
            Files.createDirectories(Path.of(UPLOAD_PATH));
            // 将文件保存到指定路径

            // 定义随机文件名
            String originalFilename = file.getOriginalFilename();
            // 拿出后缀名
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String randomFileName = UUID.randomUUID().toString() + fileExtension;

            UploadImageDIR uploadImageDIR=new UploadImageDIR(file.getOriginalFilename(), requestPath+randomFileName);
            Files.copy(file.getInputStream(), Path.of(UPLOAD_PATH, randomFileName), StandardCopyOption.REPLACE_EXISTING);
            return ResponseResult.success(uploadImageDIR);
        } catch (IOException e) {
            e.printStackTrace();

            return ResponseResult.failure(HttpStatus.INTERNAL_SERVER_ERROR, "文件上传失败");

        }
    }
    @GetMapping( "/images/{filename}")
    public ResponseEntity<Resource> getFile(@PathVariable String filename) {
        try {

            Path filePath = Paths.get(UPLOAD_PATH).resolve(filename).normalize();

            Resource resource = new UrlResource(filePath.toUri());
            if (resource.exists()) {
                return ResponseEntity.ok()
                        .contentType(MediaType.APPLICATION_OCTET_STREAM)
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }
}